package rpc_1.Client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rpc_1.interfaces.HelloService;
import rpc_1.object.HelloObject;
import rpc_1.object.RpcRequest;
import rpc_1.object.RpcResponse;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class RpcClient {
    private static final Logger logger= LoggerFactory.getLogger(RpcClient.class);

    //通过socket，把rpcrequest发送到服务器端
    public Object sendRequest(RpcRequest rpcRequest, String host, int port) {
        try(Socket socket=new Socket(host,port)){
            ObjectOutputStream objectOutputStream=new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream  objectInputStream = new ObjectInputStream(socket.getInputStream());
            objectOutputStream.writeObject(rpcRequest);
            objectOutputStream.flush();
            return objectInputStream.readObject();
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("error!:",e);
            return null;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        RpcClientProxy proxy=new RpcClientProxy("localhost",8825);
        HelloService helloService = proxy.getProxy(HelloService.class);
        HelloObject object=new HelloObject(919,"message!");
        //代理对象调用hello，会调用invoke方法
        String res = helloService.hello(object);
        System.out.println(res);
    }

}
